package cake.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import cake.dao.impl.CakeOrderDaoImpl;
import cake.dao.impl.CategoryDaoImpl;
import cake.dao.impl.UserDaoImpl;
import cake.entity.CakeOrder;
import cake.entity.Category;
import cake.entity.User;

@WebServlet("/admin/orderlist.html")
public class AdminOrderListServlet extends HttpServlet {
	private CakeOrderDaoImpl cakeOrderDaoImpl = new CakeOrderDaoImpl();
    private CategoryDaoImpl categoryDaoImpl = new CategoryDaoImpl();
    private UserDaoImpl userDaoImpl = new UserDaoImpl();
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int uid=0;
		String username="";
		if (request.getParameter("username") != null && !request.getParameter("username").isEmpty()) {
			username = request.getParameter("username");
			request.setAttribute("username",username);
			User user =userDaoImpl.fetchUserByUserName(username);
			if(user!=null) {
				uid=user.getId();
			}else {
				uid=-1;
			}
		}
		
		int cid = 0;
		if (request.getParameter("cid") != null && !request.getParameter("cid").isEmpty()) {
			cid = Integer.parseInt(request.getParameter("cid"));
			request.setAttribute("cid", cid);
		}
		String title = "";
		if (request.getParameter("title") != null && !request.getParameter("title").isEmpty()) {
			title = request.getParameter("title");
			request.setAttribute("title",title);
		}
		int pageSize = 6;
		int pageNum=1;
	    if(request.getParameter("pageNum")!=null && !request.getParameter("pageNum").isEmpty()) {
	    	pageNum=Integer.parseInt(request.getParameter("pageNum"));
	    }
           request.setAttribute("pageNum",pageNum);
		int totalpage = 0;
		totalpage = cakeOrderDaoImpl.getCount(uid,cid,title) % pageSize == 0 ? cakeOrderDaoImpl.getCount(uid,cid,title) / pageSize
				: cakeOrderDaoImpl.getCount(uid,cid,title) / pageSize + 1;
		List<CakeOrder> cakeOrders = cakeOrderDaoImpl.findAllOrder(uid,cid,title, pageNum, pageSize);
		List<Category> categories = categoryDaoImpl.getAllCategory();
		request.setAttribute("categories",categories);
		request.setAttribute("totalpage",totalpage);
		request.setAttribute("cakeOrders",cakeOrders);
		request.getRequestDispatcher("orderlist.jsp").forward(request, response);
	}
}
